package com.deep.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.deep.common.utils.HttpUtils;
import com.deep.member.dao.MemberLevelDao;
import com.deep.member.exception.LoginException;
import com.deep.member.exception.PhoneException;
import com.deep.member.exception.RegisterException;
import com.deep.member.exception.UsernameException;
import com.deep.member.model.entity.MemberLevelEntity;
import com.deep.member.model.vo.MemberUserRegisterVO;
import com.deep.member.model.vo.SocialUserDetailVO;
import com.deep.member.model.vo.SocialUserVO;
import com.deep.member.model.vo.UserLoginVO;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deep.common.utils.PageUtils;
import com.deep.common.utils.Query;

import com.deep.member.dao.MemberDao;
import com.deep.member.model.entity.MemberEntity;
import com.deep.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberUserRegisterVO vo) {
        Assert.notNull(vo, "注册vo不能为空!");

        MemberEntity memberEntity = new MemberEntity();

        // 设置默认等级【普通会员】
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        if (levelEntity == null || levelEntity.getId() == null) {
            memberEntity.setLevelId(1L);
        } else {
            memberEntity.setLevelId(levelEntity.getId());
        }

        // 检查是否已被注册
//        checkPhoneUnique(vo.getPhone());
//        checkUserNameUnique(vo.getUserName());
        checkRegister(vo.getUserName(), vo.getPhone());

        memberEntity.setNickname(vo.getUserName());
        memberEntity.setUsername(vo.getUserName());
        // 密码进行MD5加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setGender(0);
        memberEntity.setCreateTime(new Date());

        //保存数据
        baseMapper.insert(memberEntity);
    }

    @Override
    public MemberEntity login(UserLoginVO vo) {
        Assert.notNull(vo, "登录vo不能为空!");
        MemberEntity memberEntity
                = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getLoginacct()));
        if (memberEntity != null) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if (encoder.matches(vo.getPassword(), memberEntity.getPassword())) {
                return memberEntity;
            }
        }
        log.error("用户名密码错误!");
        // 用户名密码错误
        return null;
    }

    @Override
    public MemberEntity socialLogin(SocialUserVO socialUser) throws Exception {

        // 具有登录和注册逻辑

        String uid = "";
        SocialUserDetailVO giteeUserDetailVO = null;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("access_token", socialUser.getAccess_token());
            HttpResponse giteeResp = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), paramMap);
            if (giteeResp.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(giteeResp.getEntity());       // 获取到json串
                giteeUserDetailVO = JSON.parseObject(json, SocialUserDetailVO.class);
                uid = giteeUserDetailVO.getId().toString();
            }
        } catch (Exception e) {
            log.error("远程获取错误!");
            return null;
        }

        // 判断当前社交用户是否已经登录过系统
        MemberEntity memberEntity = baseMapper.selectOne(
                new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            // 用户已注册
            //TODO 从Redis更新token令牌
//            String accessToken = socialUser.getAccess_token();
//            long expires = socialUser.getExpires_in();
//            String refreshToken = socialUser.getRefresh_token();
            return memberEntity;
        } else {
            MemberEntity memberEntity1 = baseMapper.selectOne(
                    new QueryWrapper<MemberEntity>().eq("username", giteeUserDetailVO.getLogin()));
            if (memberEntity1 != null) {
                // 已经注册过，但没有绑定过uid
                memberEntity1.setSocialUid(uid);
                baseMapper.updateById(memberEntity1);

                return memberEntity1;
            } else {
                // 用户未注册
                MemberEntity member = new MemberEntity();
                // 查询当前社交用户的社交账号信息（昵称、性别等）
                assert giteeUserDetailVO != null;
                member.setUsername(giteeUserDetailVO.getLogin());
                member.setLevelId(1L);
                member.setNickname(giteeUserDetailVO.getName());
                member.setCreateTime(new Date());
                member.setSocialUid(uid);
                baseMapper.insert(member);

                return member;
            }
        }
    }

    private void checkRegister(String userName, String phone) {
        Assert.notNull(userName, "userName不能为空!");
        Assert.notNull(phone, "phone不能为空!");
        Integer count = baseMapper.selectCount(
                new QueryWrapper<MemberEntity>().eq("username", userName).or().eq("mobile", phone));
        if (count > 0) {
            throw new RegisterException();
        }
    }

}